import request from "@/utils/request";
import { tansParams } from "@/utils/common";
import { setUserInfo } from "@/utils/auth";
import Taro from "@tarojs/taro";

// 微信登录
export async function fetchWxLogin(params) {
  return request({
    url: `/applet/login/wx/login?${tansParams(params)}`,
    method: "GET",
    noLoad: true,
  });
}
// 获取手机号码
export async function fetchGetPhone(params) {
  return request({
    url: `/applet/login/getPhone?${tansParams(params)}`,
    method: "GET",
  });
}
// 登录
export async function fetchLogin(params) {
  return request({
    url: `/applet/login/login`,
    method: "POST",
    body: params,
  });
}
// 登录
export async function fetchLogout() {
  return request({
    url: `/applet/login/logout`,
    method: "POST",
  });
}
// 获取用户信息
export async function fetchGetInfo() {
  return request({
    url: `/applet/login/getInfo`,
    method: "GET",
  });
}

export function flushStorageUserInfo() {
  return new Promise(async (resolve, reject) => {
    const res = await fetchGetInfo();
    const {
      data: {
        data: {
          user: { phonenumber, nickName, avatar, idCard, userId, userType },
        },
      },
    } = res;
    Taro.removeStorageSync("USERINFO_USER");
    if (!nickName || !idCard) {
      Taro.setStorageSync("USERINFO_USER", { phonenumber, userId, userType });
      resolve(false);
    } else {
      setUserInfo({ phonenumber, nickName, avatar, idCard, userId ,userType });
      resolve(true);
    }
  });
}

// 修改用户
export async function fetchEditUser(params) {
  return request({
    url: `/applet/system/user`,
    method: "PUT",
    body: params,
  });
}
